<template>
    <el-form ref="formRef" :model="formData" :rules="validateRules">
        <el-form-item class="h-form-item" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item class="h-form-item" prop="password">
            <el-input v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item class="h-form-item">
            <el-button type="primary" @click="clickLogin(formRef)">登录</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/store/modules/user';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { loginApi } from '@/api/login/login';
import logger from '@/utils/logger';
import { HOME_ROUTE_PATH } from '@/router/static';
import type { FormInstance } from 'element-plus'
import { showErrMessage } from '@/plugins/elementPlus/message';

const router = useRouter(), currentRoute = router.currentRoute.value
const userStore = useUserStore()

const formData = reactive({
    username: "",
    password: ""
})

const validateRules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
})

const formRef = ref<FormInstance>()

const clickLogin = async (formEl: FormInstance | undefined) => {
    logger.info(formEl)
    if (!formEl) return
    formEl.validate(async (valid, fields) => {
        if (valid) {
            const result = await loginApi(formData.username, formData.password);
            if (!result.data.token) {
                showErrMessage("token缺失")
                return
            }
            userStore.setToken(result.data.token)
            logger.info("登录成功", currentRoute.query.redirect)
            router.replace((currentRoute.query.redirect ? currentRoute.query.redirect : HOME_ROUTE_PATH) as string)
        } else {
            logger.error('error submit!', fields)
        }
    })
};

</script>

<style scoped lang="scss"></style>